from sys import platform as _platform
import os
import subprocess

from codes import *



class System():
    
    """
    System controll class
    """ 

    def __init__(self):
        self._platform = self._get_platform()


    def __repr__(self):
        return f"System: {self._platform}"


    @staticmethod
    def _get_platform():
        """
        :returns Enum.Platfrom:         OS of this computer
        """
        if _platform == "win32" or "win64":
           return Platform.WINDOWS

        elif _platform == "linux" or "linux2":
           return Platform.LINUX

        elif _platform == "darwin":
           return Platform.MACOS

        else:
            return Platform.UNKNOWN


    @staticmethod
    def execute(line: str) -> (int, str):
        '''
        :param line:            Command for terminal
        
        :returns tuple:         A tuple from the state and result of execution
        '''
        if line == None:
            return Status.FAILURE, "Incorrect input!"


        try:
            result = subprocess.check_output(line, shell=True).decode("utf-8")

        except subprocess.CalledProcessError:
            code = Status.FAILURE
            result = "Error!"

        else:
            code = Status.SUCCESS

        return code, result


    @staticmethod
    def show_msgbox(msg_type: int,
        title: str,
        text: str,
        amount: int,
        file_path: str) -> (int, str):
        # TODO: platform checker
        """
        This method displays a MessageBox.

        :param msg_type:                MessageBox`s type
        :param title:                   MessageBox title
        :param text:                    MessageBox text
        :param file_path:               Output file path
        """

        if not (msg_type and title and text and amount and file_path):
            return Status.FAILURE, "Params not valid"

        response = ()

        try:
            with open(file_path, "w") as msgbox:
                msgbox.write(f'x=msgbox("{text}", {msg_type}, "{title}")')

        except:
            response = Status.FAILURE, "Can`t create file"

        else:
            response = Status.SUCCESS, "File saved"

        # Simple execution of a program is a blocking operation.
        # Therefore, implemented through 'start'
        for _ in range(amount):
            os.system(f'start "" {file_path}')
        
        return response


    @staticmethod
    def save_file(filename: str, data: bytes):
        # TODO Error checer
        # TODO: response generator
        with open(filename, "wb+") as f:
            f.write(data)
